package com.test.sshshiro.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.test.sshshiro.util.AppConstant;

@Controller
@RequestMapping
public class LoginController {
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute(AppConstant.SESSION_USER_ID);
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			subject.logout();
		}
		return "redirect:/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(String redirectURL, HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		// 把拦截前路径存下来，以便登入成功可以直接请求到登录前的页面
		ModelMap modelmap = new ModelMap();
		modelmap.addAttribute("redirectURL", redirectURL);
		view.setViewName("/login");
		view.addAllObjects(modelmap);
		return view;
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		System.out.println("failed to login=====================");
		return "redirect:/login";
	}
}
